package com.finalterm.payment.service;

import com.finalterm.payment.config.PaymentConfigProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * 支付超时管理服务
 */
@Slf4j
@Service
@RefreshScope
@RequiredArgsConstructor
public class PaymentTimeoutService {
    
    private final PaymentConfigProperties paymentConfig;
    
    /**
     * 获取当前支付超时配置
     */
    public Integer getPaymentTimeout() {
        return paymentConfig.getTimeout();
    }
    
    /**
     * 检查支付是否超时
     */
    public boolean isPaymentTimeout(long startTime) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        long timeoutMs = paymentConfig.getTimeout() * 1000L;
        
        boolean isTimeout = elapsedTime > timeoutMs;
        if (isTimeout) {
            log.warn("支付超时检测: 耗时{}ms, 超时阈值{}ms", elapsedTime, timeoutMs);
        }
        
        return isTimeout;
    }
    
    /**
     * 获取剩余超时时间（毫秒）
     */
    public long getRemainingTimeout(long startTime) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        long timeoutMs = paymentConfig.getTimeout() * 1000L;
        return Math.max(0, timeoutMs - elapsedTime);
    }
    
    /**
     * 记录支付处理时间
     */
    public void logPaymentDuration(long startTime, boolean success) {
        long duration = System.currentTimeMillis() - startTime;
        log.info("支付处理完成 - 耗时: {}ms, 超时阈值: {}ms, 结果: {}", 
                duration, paymentConfig.getTimeout() * 1000L, success ? "成功" : "失败");
    }
}
